package com.example.demo4.servlet;

import com.example.demo4.entity.Student;
import com.example.demo4.service.StudentService;
import com.example.demo4.service.impl.StudentServicelmpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;

@WebServlet(name = "StudenServlet",value = {"/StudenServlet","/getStudentByName"})
public class servlet extends HttpServlet {
    StudentService studentService = new StudentServicelmpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
        try {
            req.setAttribute("students",studentService.getStudentList());
            req.getRequestDispatcher("css.jsp").forward(req,resp);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String name = req.getParameter("name");
        String gender = req.getParameter("gender");
        String sBirthday = req.getParameter("birthday");
        LocalDate birthday = LocalDate.parse(sBirthday);
        String clazz = req.getParameter("clazz");
        String state = req.getParameter("state");
        Student student = new Student(null,name,gender,birthday,clazz,state);
        boolean flag = false;
        try {
            flag = studentService.addStudent(student);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(flag){
            req.setAttribute("msg","失败");
        }else {
            req.setAttribute("msg","成功");
        }
        req.getRequestDispatcher("msg.jsp").forward(req,resp);
    }
}
